﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    class ErrorUnlessPattern : Pattern
    {
        private Pattern pattern;

        public ErrorUnlessPattern(Pattern pattern)
            : base(PatternKind.ErrorUnless)
        {
            this.pattern = pattern;
        }

        public override PatternMatch Compile()
        {
            var p = pattern.Compile();
            return s => Target(s, p);
        }

        public static async Task<IMatch> Target(IScope scope, PatternMatch pattern)
        {
            var match = await pattern(scope);
            if (!match.Matched)
            {
                var s = scope.Stream;
                var e = new Error(new SourceSpan(s, s), ErrorSeverity.Error, "Expected value missing.");
                match = await Transformation.Match.Default(scope);
                match = match.AddErrors(e);
            }

            return match;
        }
    }
}
